#include "serial_com.h"
#include <QDebug>


Serial_com::Serial_com(QObject *parent)
    : QThread(parent)
{
    deD = new DebugDevice();
    deD->show();


    ok = true;
    myCom = NULL;
    //com_init();

    connect(this,SIGNAL(data_src(QByteArray)),this,SLOT(Read_com_date(QByteArray)), Qt::QueuedConnection);
    //heart_time->start(60000);

    port_time = new QTimer(this);
    connect(port_time, &QTimer::timeout, this, &Serial_com::portChange);
    //port_time->start(10000);

    CommedTimer = new QTimer(this);
    connect(CommedTimer, &QTimer::timeout, this, [=](){
        CommedTimer->stop();
        if(CommedList.size() > 0)
        {
            writeMyCom(CommedList.first());
            CommedList.removeFirst();
            CommedTimer->start(CommedInterval);
        }
    });

    QByteArray ba;
    ba.append(QString("12").toInt(&ok, 16));
    //QByteArray hex = ba.toHex();
    qDebug() << ba;
}

Serial_com::~Serial_com()
{
    qDebug() << "~Serial_com Close";
    if(myCom != NULL)
    {
        myCom->disconnect();
        myCom->close();
        delete myCom;
    }
}

void Serial_com::com_init(QString portName)
{
    usbName = portName;
    myCom = new QSerialPort(this);
    myCom->setPortName(usbName);//串口
    myCom->open(QIODevice::ReadWrite);
    myCom->setBaudRate(500000);//波特率
    myCom->setDataBits(QSerialPort::Data8);//数据位
    myCom->setParity(QSerialPort::NoParity);
    myCom->setStopBits(QSerialPort::OneStop);
    myCom->setFlowControl(QSerialPort::NoFlowControl);
    myCom->flush();

    connect(myCom, SIGNAL(readyRead()), this, SLOT(readMyCom()));
    connect(myCom, SIGNAL(error(QSerialPort::SerialPortError)), this, SLOT(portError(QSerialPort::SerialPortError)));
}

void Serial_com::ComClose()
{
    if(myCom != NULL)
    {
        disconnect(myCom, SIGNAL(readyRead()), this, SLOT(readMyCom()));
        disconnect(myCom, SIGNAL(error(QSerialPort::SerialPortError)), this, SLOT(portError(QSerialPort::SerialPortError)));

        myCom->close();
        delete myCom;
        myCom = NULL;
    }
}

void Serial_com::portChange()
{
    //    foreach (const QSerialPortInfo &info, QSerialPortInfo::availablePorts()) {
    //        qDebug() << "Change Name        :" << info.portName();
    //        qDebug() << "Change Description :" << info.description();
    //        qDebug() << "Change Manufacturer:" << info.manufacturer();

    //        if(info.portName().indexOf("USB Serial Port") > -1)
    //        {
    //            if(info.portName() != usbName)
    //            {
    //                if(myCom != NULL)
    //                {
    //                    disconnect(myCom, SIGNAL(readyRead()), this, SLOT(readMyCom()));
    //                    disconnect(myCom, SIGNAL(error(QSerialPort::SerialPortError)), this, SLOT(portError(QSerialPort::SerialPortError)));

    //                    myCom->close();
    //                    delete myCom;
    //                    myCom = NULL;
    //                }

    //                com_init();
    //            }
    //        }
    //    }
}

void Serial_com::portError(QSerialPort::SerialPortError error)
{
    qDebug() << error;
    if(myCom != NULL)
    {
        disconnect(myCom, SIGNAL(readyRead()), this, SLOT(readMyCom()));
        disconnect(myCom, SIGNAL(error(QSerialPort::SerialPortError)), this, SLOT(portError(QSerialPort::SerialPortError)));

        myCom->close();
        delete myCom;
        myCom = NULL;
    }
    portChange();
}

void Serial_com::Com_flush()
{
}

void Serial_com::readMyCom()
{

    //临时获得从缓存区取出来的数据，但是不确定每次取出来的是多少。
    QByteArray buffer;
    buffer = myCom->readAll();

    //qDebug() << "recv:" << buffer;

    Read_Data.append(buffer);


    quint16 mesg_len;

    int totalLen = Read_Data.size();

    while (totalLen) {

        if(totalLen < 49)
            break;

        int indexHead = Read_Data.indexOf("@");
        int indexHeadSec = Read_Data.indexOf("#");
        if(indexHead != -1 && indexHeadSec != -1)
        {
            QByteArray recv_buffer;
            recv_buffer = Read_Data.mid(indexHead, indexHeadSec - indexHead + 1);

            qDebug() << indexHead << indexHeadSec;

            emit data_src(recv_buffer);

            Read_Data = Read_Data.right(totalLen - indexHeadSec - 1);
            indexHead = Read_Data.indexOf("@");
            qDebug() << "index:" << indexHead;

            totalLen = Read_Data.length();
        }else if(indexHeadSec != -1)
        {
            Read_Data = Read_Data.right(totalLen - indexHeadSec - 1);
            indexHead = Read_Data.indexOf("#");
            qDebug() << "index:" << indexHead;

            totalLen = Read_Data.length();
        }else if(totalLen > 49)
        {
            Read_Data.clear();
            totalLen = Read_Data.length();
            break;
        }
    }
}


void Serial_com::Read_com_date(QByteArray dat)
{
    deD->recvcom(dat);
    qDebug() << "org:" << dat;
    dat = dat.mid(1, dat.length()-2);
    //qDebug() << "xeon:" << dat;

    QString dat_str = dat;

    emit Read_Com(dat_str);

    //    QStringList cmd = dat_str.split(",");
    //    QString canID = cmd.at(3);
    //    canID = canID.split("=").at(1);
    //    QByteArray orgData = cmd.at(4).toLatin1();
    //    orgData = orgData.mid(4, 16);

    //    qDebug() << "CAN ID:" << canID;
    //    qDebug() << "data:" << orgData;

}

void Serial_com::writeMyCom(QByteArray buf)
{
    qDebug() << "send:" << buf;
    deD->sendcom(buf);
    if(myCom != NULL)
    {
        myCom->write(buf);
    }
}

void Serial_com::AddSendCommedList(QByteArray buf)
{
    CommedList << buf;

    CommedTimer->start(CommedInterval);
}

void Serial_com::MainClose()
{
    qDebug() << "Main Close";
    deD->deleteLater();
    this->deleteLater();
}
